<?php
require 'TVB/pms/pdes/common/bootstrap.php';
require_once 'TVB/pms/pdes/common/util/ChangeLogTools.class.php';
/**
 * Parameters: (required)  [optional]
 *
 * Example: 
 *	Create -> update_folder.php?act=create&type=programme&id=2&folder_type=3&folder_item_type=video&title_cn=測試&title_en=test&watermark=1
 *	Update -> update_folder.php?act=update&folder_id=2&folder_type=3&title_cn=測試&title_en=test&watermark=1
 *	Delete -> update_folder.php?act=delete&folder_id=2&id=11&type=programme
 *
 * @param $id				  INT		[$programme_id | $episode_id | $cast_id | $video_id]
 * @param $type				  STRING	[programme | episode | cast | video]
 * @param $folder_id		  INT		[$folder_id]
 * @param $folder_type		  INT		[$folder_type_id]
 * @param $folder_item_type   STRING	[video | image]
 * @param $act				  STRING    (create | update | delete)
 * @param $title_cn			  STRING    [$title_cn]
 * @param $title_en			  STRING    [$title_en]
 * @param $watermark	      INT       [$watermark_id]
 * 
 */

$failed     = json_encode(array('status'=>0,'msg'=>'unsuccessful!'));
$successful = json_encode(array('status'=>1,'msg'=>'successful!'));

if( empty($_REQUEST['act']) ) exit($failed);

$id   = (int) $_REQUEST['id'];
$type = strtolower($_REQUEST['type']);

if($id<1 || !in_array($type,array('programme','episode','cast','video'))) exit($failed);

$action = strtolower($_REQUEST['act']);
switch($action){
	case 'create':
	case 'update':
	case 'delete':
		$fun = 'folder_'.$action;
		Model::$dbo['w']->beginTransaction();
		try{
			$update_obj = Model::$dbo['w']->find($type,'id=?',array($id));
			if(!$update_obj) throw new Exception("$type id $id not exists!");
			$update_obj = $update_obj[0];

			# change_log
			$change_log = array();

			$fun($update_obj,$change_log);
			Model::$dbo['w']->commit();

			array_walk($change_log,'change_log::updateOne');

			exit($successful);
		}catch(Exception $e){
			Model::$dbo['w']->rollBack();
			$msg = $e->getMessage();
			exit(json_encode(array('status'=>0,'msg'=>$msg)));
		}
	break;
	default: exit($failed);
}


function folder_create($update_obj, &$change_log){
	$folder_type_id   = (int) $_REQUEST['folder_type'];
	$folder_item_type = $_REQUEST['folder_item_type'];
	if(strtolower($folder_item_type) == 'image'){
		$folder_item_type_id = AC::FOLDER_TYPE_IMAGE;
		$is_image_folder = true;
	}else{
		$folder_item_type_id = AC::FOLDER_TYPE_VIDEO;
		$is_image_folder = false;
	}
	$folders = array_filter(explode(',',$update_obj->folders));
	$folder_type_obj = Model::$dbo['w']->find('folder_type','id=?',array($folder_type_id));
	if(empty($folder_type_obj)) throw new Exception('folder_type not exists!');
	$folder_type_obj = $folder_type_obj[0];

	if($folder_type_obj->folder_item_type_id != $folder_item_type_id) throw new Exception('folder_type->folder_item_type_id != folder_item_type');

	$zh_lang_id = language::getLanguageID(AC::LANGUAGE_ZH);
	$en_lang_id = language::getLanguageID(AC::LANGUAGE_EN);
	$title_cn   = $_REQUEST['title_cn'];
	$title_en   = $_REQUEST['title_en'];

	$ok = check_folder_name($update_obj->folders,array(':id'=>0,':cn'=>$zh_lang_id,':en'=>$en_lang_id,':title_cn'=>$title_cn,':title_en'=>$title_en,':folder_item_type_id'=>$folder_item_type_id));
	if(!$ok) throw new Exception('folder name already exists!');

	switch($update_obj->getTableName()){
	case 'programme':
		$change_data = array('programme_id'=>$update_obj->id, 'episode_id'=>array());
		break;
	case 'episode':
		$change_data = array('programme_id'=>0, 'episode_id'=>array($update_obj->id));
		break;
	case 'cast':
		$change_data = ChangeLogTools::getEpisodeIdsByCastId($update_obj->id);
	}
	$change_data['is_active'] = 1;
	$change_data['is_publish'] = 0;

	$folder = new folder();
	$folder->folder_type_id      = $folder_type_id;
	$folder->folder_item_type_id = $folder_item_type_id;
	$folder->system_label        = $folder_type_obj->system_label;
	$folder->status              = AC::STATUS_NEW;
	$folder->created_at          = date('c');
	$folder->created_by          = CommonUtils::get_user();
	$folder->modified_at         = $folder->created_at;
	$folder->modified_by         = $folder->created_by;
	$folder_id = Model::$dbo['w']->save($folder);
	# change_log
	$change_data['type'] = 'folder';
	$change_data['keys'] = array('id'=>$folder_id);
	$change_log[] = $change_data;

	$folder_language = new folder_language();	
	$folder_language->folder_id   = $folder_id;
	$folder_language->language_id = $zh_lang_id;
	$folder_language->title       = $title_cn;
	Model::$dbo['w']->save($folder_language);
	# change_log
	$change_data['type'] = 'folder-language';
	$change_data['keys'] = array('folder_id'=>$folder_id,'language_id'=>$zh_lang_id);
	$change_log[] = $change_data;

	$folder_language->folder_id   = $folder_id;
	$folder_language->language_id = $en_lang_id;
	$folder_language->title       = $title_en;
	Model::$dbo['w']->save($folder_language);
	# change_log
	$change_data['type'] = 'folder-language';
	$change_data['keys'] = array('folder_id'=>$folder_id,'language_id'=>$en_lang_id);
	$change_log[] = $change_data;


	if($is_image_folder){
		Model::updateBySql('delete from `image_folder-config` where folder_id='.$folder_id);
		Model::updateBySql('insert into `image_folder-config` values('.$folder_id.','.(int)$_REQUEST['watermark'].')');
		# change_log
		$change_data['type'] = 'image_folder-config';
		$change_data['keys'] = array('folder_id'=>$folder_id);
		$change_log[] = $change_data;
	}

	$folders[] = $folder_id;
	$folders = array_unique($folders);

	$update_obj->folders = implode(',',$folders);
	Model::$dbo['w']->save($update_obj);
	# change_log
	$change_data['type'] = $update_obj->getTableName();
	$change_data['keys'] = array('id'=>$update_obj->id);
	$change_log[] = $change_data;
}

function folder_update($update_obj, &$change_log){
	$folder_id        = (int) $_REQUEST['folder_id'];
	$folder_type_id   = (int) $_REQUEST['folder_type'];
	$folder_item_type = $_REQUEST['folder_item_type'];

	if(empty($folder_id)) throw new Exception('folder_id error');

	$folder = Model::$dbo['w']->find('folder','id=?',array($folder_id));
	if(empty($folder)) throw new Exception('folder not exists!');
	$folder = $folder[0];

	$folder_type_obj = Model::$dbo['w']->find('folder_type','id=?',array($folder_type_id));
	if(empty($folder_type_obj)) throw new Exception('folder_type not exists!');
	$folder_type_obj = $folder_type_obj[0];

	if(strtolower($folder_item_type) == 'image'){
		$folder_item_type_id = AC::FOLDER_TYPE_IMAGE;
		$is_image_folder = true;
	}else{
		$folder_item_type_id = AC::FOLDER_TYPE_VIDEO;
		$is_image_folder = false;
	}

	if($folder_type_obj->folder_item_type_id != $folder_item_type_id) throw new Exception('folder_type->folder_item_type_id != folder_item_type');

	$zh_lang_id = language::getLanguageID(AC::LANGUAGE_ZH);
	$en_lang_id = language::getLanguageID(AC::LANGUAGE_EN);
	$title_cn   = $_REQUEST['title_cn'];
	$title_en   = $_REQUEST['title_en'];

	$ok = check_folder_name($update_obj->folders,array(':id'=>$folder_id,':cn'=>$zh_lang_id,':en'=>$en_lang_id,':title_cn'=>$title_cn,':title_en'=>$title_en,':folder_item_type_id'=>$folder_item_type_id));
	if(!$ok) throw new Exception('folder name already exists!');

	switch($update_obj->getTableName()){
	case 'programme':
		$change_data = array('programme_id'=>$update_obj->id, 'episode_id'=>array());
		break;
	case 'episode':
		$change_data = array('programme_id'=>0, 'episode_id'=>array($update_obj->id));
		break;
	case 'cast':
		$change_data = ChangeLogTools::getEpisodeIdsByCastId($update_obj->id);
	}
	$change_data['is_active']  = 1;
	$change_data['is_publish'] = 0;

	$folder->folder_type_id      = $folder_type_id;
	$folder->folder_item_type_id = $folder_item_type_id;
	$folder->modified_at         = date("Y-m-d H:i:s");
	$folder->modified_by         = CommonUtils::get_user();
	Model::$dbo['w']->save($folder);
	# change_log
	$change_data['type'] = 'folder';
	$change_data['keys'] = array('id'=>$folder_id);
	$change_log[] = $change_data;

	//for bug:7478     #added by Albie Lu on 2011-10-21
	$sql = "select item_id from folder_item where folder_id=:folder_id";
	$arr = array(":folder_id"=>$folder_id);
	$folder_items = Model::selectBySql($sql,$arr);
	foreach($folder_items as $v){
		$change_data['type'] = 'image';
		$change_data['keys'] = array('id'=>	$v['item_id']);
		$change_log[] = $change_data;
	}

	
	Model::updateBySql('delete from `folder-language` where folder_id=:fid',array(':fid'=>$folder_id));
	$sql = 'insert into `folder-language` values(:fid,:lid,:title,"")';
	Model::updateBySql($sql ,array(':fid'=>$folder_id,':lid'=>$zh_lang_id,':title'=>$title_cn));
	Model::updateBySql($sql ,array(':fid'=>$folder_id,':lid'=>$en_lang_id,':title'=>$title_en));
	# change_log
	$change_data['type'] = 'folder-language';
	$change_data['keys'] = array('folder_id'=>$folder_id,'language_id'=>$zh_lang_id);
	$change_log[] = $change_data;
	$change_data['type'] = 'folder-language';
	$change_data['keys'] = array('folder_id'=>$folder_id,'language_id'=>$en_lang_id);
	$change_log[] = $change_data;

	if($is_image_folder){
		Model::updateBySql('delete from `image_folder-config` where folder_id='.$folder_id);
		Model::updateBySql('insert into `image_folder-config` values('.$folder_id.','.(int)$_REQUEST['watermark'].')');
		# change_log
		$change_data['type'] = 'image_folder-config';
		$change_data['keys'] = array('folder_id'=>$folder_id);
		$change_log[] = $change_data;
	}
}

function folder_delete($update_obj, &$change_log){
	$folders = array_filter(explode(',',$update_obj->folders));
	$folder_id = (int) $_REQUEST['folder_id'];
	$index = array_search($folder_id,$folders);
	unset($folders[$index]);
	$update_obj->folders = implode(',',$folders);
	Model::$dbo['w']->save($update_obj);

	# change_log
	switch($update_obj->getTableName()){
	case 'programme':
		$change_data = array('programme_id'=>$update_obj->id, 'episode_id'=>array());
		break;
	case 'episode':
		$change_data = array('programme_id'=>0, 'episode_id'=>array($update_obj->id));
		break;
	case 'cast':
		$change_data = ChangeLogTools::getEpisodeIdsByCastId($update_obj->id);
	}
	$change_data['is_active'] = 0;
	$change_data['is_publish'] = 0;

	if(folder::is_image_folder($folder_id)){
		Model::updateBySql('delete from `image_folder-config` where folder_id='.$folder_id);
		# change_log
		$change_data['type'] = 'image_folder-config';
		$change_data['keys'] = array('folder_id'=>$folder_id);
		$change_log[] = $change_data;
	}
	Model::updateBySql('delete from `folder-language` where folder_id='.$folder_id);
	Model::updateBySql('delete from folder where id='.$folder_id);

	# change_log
	$zh_lang_id = language::getLanguageID(AC::LANGUAGE_ZH);
	$en_lang_id = language::getLanguageID(AC::LANGUAGE_EN);
	$change_data['type'] = 'folder';
	$change_data['keys'] = array('id'=>$folder_id);
	$change_log[] = $change_data;
	$change_data['type'] = 'folder-language';
	$change_data['keys'] = array('folder_id'=>$folder_id,'language_id'=>$zh_lang_id);
	$change_log[] = $change_data;
	$change_data['type'] = 'folder-language';
	$change_data['keys'] = array('folder_id'=>$folder_id,'language_id'=>$en_lang_id);
	$change_log[] = $change_data;
}


function check_folder_name($old_folders,$param){
	if(empty($old_folders)) return true;
	$sql = "
		SELECT f.id
		FROM folder f 
			INNER JOIN `folder-language` fl_1 ON (f.id=fl_1.folder_id) 
			LEFT  JOIN `folder-language` fl_2 ON (f.id=fl_2.folder_id) 
			   AND (fl_1.folder_id=fl_2.folder_id)
			   AND (fl_1.language_id=:cn) 
			   AND (fl_2.language_id=:en)
		WHERE (f.folder_item_type_id=:folder_item_type_id)
			AND (f.id<>:id) 
			AND (IFNULL(fl_1.title,'')=:title_cn) 
			AND (IFNULL(fl_2.title,'')=:title_en) 
			AND (fl_1.folder_id IN($old_folders))
	";
	$folders = Model::selectBySql($sql,$param);
	if(isset($folders[0]['id'])) return false;
	return true;
}
?>
